<?php

namespace App\Containers\AppSection\Profile\Tasks;

use App\Containers\AppSection\Profile\Data\Repositories\ProfileRepository;
use App\Containers\AppSection\Profile\Models\Profile;
use App\Ship\Criterias\OrderByCreationDateDescendingCriteria;
use App\Ship\Criterias\ThisUserCriteria;
use App\Ship\Exceptions\NotFoundException;
use App\Ship\Parents\Tasks\Task;
use Exception;

class FindLatestProfileByUserIdTask extends Task
{
    protected ProfileRepository $repository;

    public function __construct(ProfileRepository $repository)
    {
        $this->repository = $repository;
    }

    public function run($userId): Profile
    {
        try {
            return $this->repository
                ->pushCriteria(new OrderByCreationDateDescendingCriteria())
                ->pushCriteria(new ThisUserCriteria($userId))
                ->first();
        } catch (Exception $exception) {
            throw new NotFoundException(__('ship::resource.not-found'));
        }
    }
}
